package com.vkdroid.xmpp;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.RemoteException;

import java.util.HashMap;

/**
 * Created by Vladimir Grachev.
 * Date: Aug 29, 2010
 * Time: 1:31:10 PM
 */
public class XmppUtils {

    private static IXmppService mService = null;
    private static HashMap<Context, ServiceBinder> sConnectionMap = new HashMap<Context, ServiceBinder>();

    public static boolean bindToService(Context context, IXmppServiceCallback callback) {
        context.startService(new Intent(context, XmppService.class));
        if (sConnectionMap.get(context) == null) {
            ServiceBinder sb = new ServiceBinder(callback);
            sConnectionMap.put(context, sb);
            return context.bindService((new Intent()).setClass(context, XmppService.class), sb, 0);
        }
        return false;
    }

    public static void unbindFromService(Context context) {
        ServiceBinder sb = (ServiceBinder)sConnectionMap.remove(context);
        if (sb == null) {
            return;
        }
        if (sb.mCallback != null && mService != null) {
            try {
                mService.unregisterCallback(sb.mCallback);
            } catch (RemoteException e) {
            }
        }
        sb.mCallback = null;
        context.unbindService(sb);
        if (sConnectionMap.isEmpty()) {
            mService = null;
        }
    }

    public static IXmppService getXmppService() {
        return mService;
    }

    private static class ServiceBinder implements ServiceConnection {
        IXmppServiceCallback mCallback;

        ServiceBinder(IXmppServiceCallback callback) {
            mCallback = callback;
        }

        public void onServiceConnected(ComponentName className, android.os.IBinder service) {
            mService = IXmppService.Stub.asInterface(service);
            try {
                if (mCallback != null) {
                    mService.registerCallback(mCallback);
                    mCallback.onServiceReady();
                }
            } catch (RemoteException e) {
            }
        }

        public void onServiceDisconnected(ComponentName className) {
            if (mCallback != null && mService != null) {
                try {
                    mService.unregisterCallback(mCallback);
                } catch (RemoteException e) {
                }
            }
            mCallback = null;
        }
    }

}
